package anonymouschat.client.frames;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import anonymouschat.client.Client;
import anonymouschat.client.Identity;
import anonymouschat.messages.Message;
import anonymouschat.messages.TextMessage;
import anonymouschat.messages.securitymessages.TextMessageWithSig;
import anonymouschat.security.SecurityUtils;
import anonymouschat.security.integrity.DigSig;
import anonymouschat.utils.LocalFileOps;
import anonymouschat.utils.Print;

/**
 * One on one chat frame, only supply two people to chat. ownerUser is the local
 * client, while targetUser is the user owner is chatting with.
 * 
 * @author Winters
 */
public class OneOnOneChatFrame extends JFrame {
	private static final long serialVersionUID = 1L;

	private HashMap<String, ArrayList<String>> tempChatLog;

	HashMap<String, OneOnOneChatFrame> oneOnOneChatList;

	private Identity ownerIdentity;

	private String ownerUserID;

	private String targetUserID;

	public JTextArea textArea;

	private JTextArea msgArea;

	private JScrollPane textScr;

	private JScrollPane msgScr;

	private JButton sendButton;

	private static final int WIDTH = 400;

	private static final int HEIGHT = 500;

	private Client client;

	/**
	 * Constructor by two user names and chatLog, outStream
	 * 
	 * @param owner
	 * @param target
	 * @param tempChatLog
	 * @param out
	 * @param oneOnOneChatList
	 */
	public OneOnOneChatFrame(Client client, Identity owner, String target,
			HashMap<String, ArrayList<String>> tempChatLog,
			HashMap<String, OneOnOneChatFrame> oneOnOneChatList) {
		this.client = client;
		this.tempChatLog = tempChatLog;
		this.oneOnOneChatList = oneOnOneChatList;
		ownerUserID = owner.getUserName();
		targetUserID = target;
		ownerIdentity = owner;

		// main frame
		setTitle("Chatting with " + targetUserID);
		setSize(WIDTH, HEIGHT);
		setVisible(true);
		setResizable(false);
		getContentPane().setLayout(null);
		addWindowListener(new WindowAdapter() {
			@Override
            public void windowClosing(WindowEvent e) {
				closingWindow();
				dumpChatLog();
			}
		});

		// textArea
		textArea = new JTextArea();
		textArea.setEditable(false);
		textScr = new JScrollPane(textArea);
		textScr.setSize(WIDTH, HEIGHT - 100);
		textScr.setLocation(0, 0);

		// sendMsg
		msgArea = new JTextArea();
		msgScr = new JScrollPane(msgArea);
		msgScr.setLocation(10, HEIGHT - 90);
		msgScr.setSize(WIDTH - 130, 50);

		// sendButton
		sendButton = new JButton("Send");
		sendButton.setLocation(WIDTH - 120, HEIGHT - 90);
		sendButton.setSize(100, 50);
		sendButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				sendTextMsg(msgArea.getText());
				msgArea.setText("");
			}
		});

		this.getContentPane().add(textScr);
		this.getContentPane().add(msgScr);
		this.getContentPane().add(sendButton);
		this.validate();
	}

	private void closingWindow() {
		this.oneOnOneChatList.remove(targetUserID);
		dispose();
	}

	/**
	 * Save tempChatLog to file.
	 * 
	 * @throws IOException
	 */
	private void dumpChatLog() {
		for (Map.Entry<String, ArrayList<String>> entry : tempChatLog
				.entrySet()) {
			String dstUserName = entry.getKey();
			if (dstUserName.equals(targetUserID)) {
				ArrayList<String> msgList = entry.getValue();
				StringBuffer sb = new StringBuffer();
				for (String s : msgList) {
					sb.append(s);
				}
				try {
					LocalFileOps.appendChatHist(ownerIdentity, dstUserName,
							sb.toString());
				} catch (ClassNotFoundException e) {
					Print.error("Error appending ChatHist", e);
				}
				entry.getValue().clear();
			}
		}
	}

	/**
	 * Wrap text message obj with signature, call sendChatMessage.
	 * 
	 * @param text
	 */
	private void sendTextMsg(String text) {

		String tempData = "You" + "\n" + new Date() + "\n" + text + "\n\n";
		textArea.append(tempData);
		if (tempChatLog.containsKey(targetUserID)) {
			tempChatLog.get(targetUserID).add(tempData);
		} else {
			tempChatLog.put(targetUserID, new ArrayList<String>());
			tempChatLog.get(targetUserID).add(tempData);
		}
		TextMessage msg = new TextMessage(ownerUserID, targetUserID, text);
		DigSig signature = SecurityUtils.sign(msg, this.client.getIdentity()
				.getSigningKey());
		TextMessageWithSig msgWithSig = new TextMessageWithSig(msg, signature);

		Print.sending(ownerUserID, "Sending Text Message");
		Print.debug((Message) msgWithSig);
		client.sendChatMessage(msgWithSig);
	}
	
	public void showMsgInWindow(String text){
		textArea.append("\n" + text + "\n");
	}
}
